package com.myna.csv.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class DomainRdcMappingMetadataUtil {

    public static Map<Long, String> getJsonMapping(String fileName) {
        String jsonStr = ReadFile(fileName).toString();
        JSONArray jsonArray = JSONArray.fromObject(jsonStr);
        Map<Long, String> map = new HashMap<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            map.put(jsonObject.getLong("id"), jsonObject.getString("name"));
        }
        return map;
    }

    private static StringBuffer ReadFile(String fileName) {
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            InputStream inputStream = DomainRdcMappingMetadataUtil.class.getClassLoader().getResourceAsStream(fileName);
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                sbf.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sbf;
    }
}
